<template>
  <div class="app-container flex column">
    <top-title :cusString="cusString" :policeView="true"></top-title>
    <div class="content-wrap f1 flex column">
      <!-- 搜索栏 -->
      <div class="search-group">
        <div class="input-wrap">
          <div class="label">选择时间:</div>
          <div class="input-item">
            <a-month-picker
              v-model="queryParam.value"
              :allowClear="false"
              :disabled-date="disabledDate"
              value-format="YYYY-MM"
              @change="timeChange"
            />
          </div>
        </div>

        <div class="btn-wrap">
          <a-button class="searchBtn" type="primary" @click="searchQuery()"> 搜索 </a-button>
          <a-button class="resetBtn" type="primary" @click="searchReset()"> 重置 </a-button>
        </div>

        <!-- <div class="btn-group">
          <a-button
            class="exportBtn"
            @click="handleExportXls(`${cusString}`, { startTime: queryParam.startTime, endTime: queryParam.endTime })"
            type="primary"
          >
            导出Excel
          </a-button>
        </div> -->
      </div>

      <div class="table-wrap f1">
        <a-table
          id="a-table"
          :columns="cusColumns"
          :dataSource="dataSource"
          :pagination="ipagination"
          :scroll="{ x: 999 }"
          bordered
          class="tableList"
          rowKey="id"
          @change="handleTableChange"
        >
          <template v-for="col in colDataIndexList" #[col]="text, record">
            <div :key="col">
              <!-- :read-only="readonlyArr.includes(col)" -->
              <!--  :disabled="!record[col + '_detailId']" -->
              <a-input
                v-if="record.editable && record[col + '_detailId']"
                :value="text"
                placeholder="请输入"
                @change="(e) => handleChange(e.target.value, record.id, col, record)"
              />
              <a-input
                v-else-if="record.editable && !record[col + '_detailId']"
                :disabled="!record[col + '_detailId']"
                :value="text"
                placeholder="不能修改"
              />
              <!-- <div v-else-if="record.editable && !record[col + '_detailId']" style="color: red">不能修改</div> -->
              <span v-else>{{ text }} </span>
            </div>
          </template>
          <template #action="record">
            <div v-if="record.editable">
              <span class="operation deatil-color" @click="save(record.id)">保存</span>
              <a-divider type="vertical" />
              <span class="operation deatil-color" @click="cancel(record.id)">取消</span>
            </div>
            <div v-else>
              <span
                v-if="$moment().startOf('month').format('YYYY/MM') === record.month_date"
                class="operation deatil-color"
                @click="edit(record.id)"
                >编辑</span
              >
              <div v-else style="color: f2f2f2">编辑</div>
            </div>
          </template>
        </a-table>
      </div>
    </div>
  </div>
</template>

<script>
import { putAction } from '@/api/manage'
import topTitle from '@/components/topTitle'
import startEndTime from '@/components/startEndTime'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { getAction } from '@/api/manage'
export default {
  name: 'policeInspector',
  components: { topTitle, startEndTime },
  mixins: [JeecgListMixin],
  data() {
    return {
      cusString: '民警评分规则',
      url: {
        list: '/police/staion/ruleList',
        put: '/police/staion/ruleUpdate',
        exportXlsUrl: '/police/staion/directorOfAnInstitute/page/export',
      },
      disableMixinCreated: true,
      columns: [
        {
          title: '时间',
          width: 150,
          ellipsis: true,
          align: 'center',
          dataIndex: 'month_date',
        },
      ],
      curMonth: '',
      cusColumns: [],
      colDataIndexList: [],
      cacheData: [],
      paramsObj: {},
    }
  },
  mounted() {
    this.loadData()
  },
  methods: {
    disabledDate(current) {
      return current && current > this.$moment().endOf('day')
    },
    timeChange(v, index) {
      this.$forceUpdate()
      this.queryParam.startTime = this.$moment(this.queryParam.value).startOf('month').valueOf()
      this.queryParam.endTime = this.$moment(this.queryParam.value).endOf('month').valueOf()
    },

    searchReset() {
      this.queryParam = {}
      this.loadData()
    },

    async loadData() {
      this.queryParam.pageNo = this.ipagination.current
      this.queryParam.pageSize = this.ipagination.pageSize
      let { result } = await getAction(this.url.list, this.queryParam)
      this.cusColumns = this.columns.concat(result.keyName)
      this.allChildrenAddValue(this.cusColumns) //递归塞值
      this.dataSource = result.page.records
      this.ipagination.total = result.page.total

      let node = {
        title: '操作',
        width: 150,
        align: 'center',
        scopedSlots: { customRender: 'action' },
      }
      this.cusColumns.push(node)
    },

    allChildrenAddValue(node) {
      for (const item of node) {
        if (item.title && item.title !== '时间' && !item.children) {
          item.width = 100
          item.align = 'center'
          item.scopedSlots = { customRender: item.dataIndex }
          this.colDataIndexList.push(item.dataIndex)
        }
        if (item.children) {
          this.allChildrenAddValue(item.children)
        }
      }
      return node
    },

    // 编辑一行
    edit(rowKey) {
      const newData = [...this.dataSource]
      const target = newData.filter((item) => rowKey === item.id)[0]
      // 根据rowKey判断该行数据是否存在
      if (target) {
        target.editable = true // 修改target可以直接影响到newData
        this.dataSource = newData
      }
    },

    // 点击保存
    async save(rowKey) {
      console.log(this.paramsObj, 'params')

      let { result } = await putAction(this.url.put, this.paramsObj)
      console.log(result)

      this.loadData()
      // const newData = [...this.dataSource]
      // const target = newData.filter(item => rowKey === item.id)[0]
      // if (target) {
      //   delete target.editable
      //   this.dataSource = newData
      //   // this.cacheData = newData.map(item => ({ ...item }))
      // }
    },
    // 点击取消
    cancel(rowKey) {
      const newData = [...this.dataSource]
      const target = newData.filter((item) => rowKey === item.id)[0]
      if (target) {
        // 将缓存数据中匹配到的数据对象覆盖合并当前被修改的行
        Object.assign(target, this.cacheData.filter((item) => rowKey === item.id)[0])
        delete target.editable
        this.dataSource = newData
      }
    },

    // input 输入change
    handleChange(value, rowKey, colName, record) {
      this.paramsObj[[record[colName + '_detailId']]] = Number(value)

      const newData = [...this.dataSource]
      const target = newData.filter((item) => rowKey === item.id)[0]

      if (target) {
        target[colName] = value
        this.dataSource = newData
      }
    },

    // 导出当前页
    exportExcel() {
      const wb = XLSX.utils.table_to_book(document.querySelector('#a-table'))

      const wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array',
      })
      try {
        fs.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '检查数据.xlsx')
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
    },
  },
  destroy() {},
}
</script>

<style lang="less" scoped>
/deep/ .ant-table-body {
  border: 1px solid #0a5297 !important;
  .ant-table-thead > tr > th,
  .ant-table-tbody > tr > td {
    border: 1px solid #0a5297 !important;
  }
}

/deep/ .ant-table-row-cell-break-word {
  .ant-input {
    // height: 40px;
    font-size: 0.16rem;
    background: var(--theme-input-bg);
    border-radius: 0.04rem;
    border: 1px solid #13497a;
    color: var(--theme-modal-label-value-color);
    &::placeholder {
      color: #1163b8;
    }
  }

  .ant-input-prefix {
    color: #0f5eb3;
  }
}

// /deep/ .ant-table-row-cell-break-word:hover {
//   background: #1388ff !important;
//   cursor: pointer;
// }

.app-container {
  background: var(--theme-content-bg);
  padding-top: 0;
  padding-bottom: 0;
  .content-wrap {
    background: var(--theme-container-bg);
    overflow: hidden;
    .table-wrap {
      padding: 0 20px;
      overflow: auto;
    }
  }
}
</style>
